package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Families;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map, HttpSession session) {
//        1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
        String validateCode = (String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        Jedis jedis = jedisPool.getResource();
        String validateCodeRedis = jedis.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (validateCode != null && validateCodeRedis != null && validateCode.equals(validateCodeRedis)) {
//             2、如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                member = new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            /*5.登录成功 将member_id存入session显示登录状态*/
            String id = memberService.findByTelephone(telephone).getId().toString();
            session.setAttribute("member_id", Integer.parseInt(id));

            //          3、向客户端写入Cookie，内容为用户id
            Cookie cookie = new Cookie("login_member_id", id);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);


//        4、将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
            String json = JSON.toJSON(member).toString();
            jedis.setex(telephone, 60 * 30, json);
            jedis.close();
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }

    @RequestMapping("/loginM")
    public Result loginM(HttpServletResponse response, @RequestBody Map map, HttpSession session) {
        String checkmember = map.get("checkmember").toString();
        String password = map.get("password").toString();
        Member member = new Member();
        password = MD5Utils.md5(password);
        if (checkmember.contains("@")) {
            try {
                member = memberService.findMemByEMeilAndPsw(checkmember, password);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "登录失败");
            }
        } else if (Pattern.matches("(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)", checkmember)) {
            try {
                member = memberService.findMemByIDCAndPsw(checkmember, password);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "登录失败");
            }

        } else {
            try {
                member = memberService.findMemByPhoneAndPsw(checkmember, password);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "登录失败");
            }
        }
        if (member == null) {
            return new Result(false, "登录失败");
        }
        String id = memberService.findByTelephone(member.getPhoneNumber()).getId().toString();
        session.setAttribute("member_id", Integer.parseInt(id));

        //          3、向客户端写入Cookie，内容为用户id
        Cookie cookie = new Cookie("login_member_id", id);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30);
        response.addCookie(cookie);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }

    @RequestMapping("/findFamilies")
    public Result findFamilies(HttpSession session) {
        Object member_id = session.getAttribute("member_id");
        List<Families> list = memberService.findFamiliesByMemberId(Integer.parseInt(member_id.toString()));
        if (list == null) {
            return new Result(false, "无对应关系人信息");
        } else {
            return new Result(true, "已加载关系人信息", list);
        }
    }

    //根据用户id来查找用户信息
    @RequestMapping("/findUserById")
    public Result findUserById(Integer id) {
        try {
            Member member = memberService.findById(id);
            return new Result(true, "查找用户信息成功", member);
        } catch (Exception e) {
            return new Result(false, "查找用户信息失败");
        }
    }

    //更新用户个人信息
    @RequestMapping("/submit")
    public Result submit(@RequestBody Member member) {
        try {
            memberService.update(member);
            return new Result(true, "更新成功");
        } catch (Exception e) {
            return new Result(false, "更新失败");
        }
    }

    /**
     * 查询用户原密码是否填写正确
     *
     * @param id
     * @param password
     * @return
     */
    @RequestMapping("/findPassword")
    public Result findPassword(Integer id, String password) {
        try {
            Member member = memberService.findById(id);
            if (!member.getPassword().equals(password)) {
                return new Result(false, "原密码错误，请重新输入");
            } else {
                return new Result(true, "原密码正确");
            }

        } catch (Exception e) {
            return new Result(false, "查询失败");
        }
    }

    @RequestMapping("/submitPass")
    public Result submitPass(@RequestBody Map map) {
        String telephone = (String) map.get("phoneNumber");
        Jedis jedis = jedisPool.getResource();
        String s = jedis.get(telephone + RedisMessageConstant.SENDTYPE_PASS);
        jedis.close();
        String validateCode = (String) map.get("validateCode");
        if (validateCode == null || !validateCode.equals(s)) {
            //验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        } else {
            //验证码正确
            Member member = new Member();
            Set set = map.keySet();
            for (Object o : set) {
                String s1 = (String) o;
                if (s1.equals("id")) {
                    member.setId((Integer) map.get(o));
                } else if (s1.equals("password3")) {
                    member.setPassword((String) map.get(o));
                }
            }
            memberService.update(member);
            return new Result(true, "修改成功，请重新登录");
        }
    }
}
